<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>web-socket-chat</title>
    <style>
        *{margin: 0;padding: 0;}
        ul,ol li{list-style: none;}
        ul li{border-bottom: 1px dashed #ccc;padding: 10px 5px 5px 5px;}
        .sys_msg{text-align: left;}
        .my_msg{text-align: right;}
        #box{
            padding: 10px;
            border: 1px solid #ccc;
            width: 500px;
            height: 300px;
            overflow-y:auto;
        }
    </style>
</head>
<body>
    <div id="box">
        <ul>
            <!--<li class="sys_msg">小娜：你好</li>-->
            <!--<li class="my_msg">我：你好</li>-->
        </ul>
    </div>
    <br>
    <p>
        <textarea name="content" id="content" style="width: 515px;height: 100px;"></textarea>
        <p>
            <button type="button" onclick="connect();">连接</button>
            <button type="button" onclick="disconnect();">断开连接</button>
            <button type="button" onclick="get_state();">查看连接状态</button>
            <button type="button" onclick="send_msg();">发送</button>
        </p>
    </p>

<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
<script>
    function send_msg() {
        var content = $("#content").val();
        console.log(content);
        if (ws) {
            if (content.length > 0) {
                log_my_msg(content);
                ws.send(content);
                $("#content").val('');
            }
        } else {
            log_sys_msg('还未建立连接');
        }
    }

    var ws;

    function log_sys_msg(msg){
        var tpl = '<li class="sys_msg msg">小娜：'+msg+'</li>';
        $("#box ul").append(tpl);
        scroll_ctl();
    }

    function log_my_msg(msg){
        var tpl = '<li class="my_msg msg">我：'+msg+'</li>';
        $("#box ul").append(tpl);
        scroll_ctl();
    }

    function scroll_ctl(){
        $('#box').scrollTop( $('#box')[0].scrollHeight);
    }

    function connect(){
        try {
            ws = new WebSocket("ws://127.0.0.1:8001");//连接服务器
            ws.onopen = function(event){log_sys_msg("已经与服务器建立了连接 当前连接状态："+this.readyState);};
            ws.onmessage = function(event){log_sys_msg("接收到服务器发送的数据："+event.data);};
            ws.onclose = function(event){log_sys_msg("已经与服务器断开连接 当前连接状态："+this.readyState);};
            ws.onerror = function(event){log_sys_msg("WebSocket异常！");};
        } catch (ex) {
            log_sys_msg(ex.message);
        }
    }

    function disconnect(){
        ws.close();
    }

    function get_state(){
        if(ws){
            log_sys_msg('当前连接状态：'+ws.readyState);
        }else{
            log_sys_msg('还未建立连接');
        }
    }
</script>
</body>
</html>